<script setup lang="ts">
import { onMounted, reactive, nextTick, ref } from 'vue'
import { useRoleStore, useFuncStore } from '@/store'
import { Edit, Setting, Delete, Finished, Close, RefreshRight } from '@element-plus/icons-vue'
import { httpBatch } from '@/util/http';
import { RoleAPI } from '@/api'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'

const funcStore = useFuncStore()
const roleStore = useRoleStore()
const treeRef = ref<any>(null)
const roleFunc = reactive<{
    isSetting: boolean,
    isCart: boolean,
    currentFuncs: Vm.Func[],
    model: HttpPayload.RoleFunc
}>({
    isSetting: false,
    isCart: false,
    currentFuncs: [],
    model: { role_id: 0, role_func_ids: "" }
});
const roleModel = reactive({ role_id: 0, role_name: "" });

//单元格宽度
const formLabelWidth = '80px';

const formRef = ref<FormInstance | null>(null);
//定制表单校验规则
const rules = {
    role_name: [
        { required: true, message: '*角色名称不能为空', trigger: "blur" },
        { min: 2, max: 20, message: '*角色名称长度2 - 20', trigger: "blur" }
    ]
}

//钩子函数、到仓库拿数据
onMounted(async () => {
    try {
        await httpBatch([() => roleStore.init(), () => funcStore.init()])
    } catch (e) { console.log(e) }
})

// 回显当前角色功能
const echoFuncs = () => {
    const checkedKeys = roleFunc.currentFuncs.reduce((result: Number[], item: Vm.Func) => {
        if (item.func_key !== '') result.push(item.func_id);
        return result;
    }, []);
    //重置
    treeRef.value.setCheckedKeys(checkedKeys);
}
//绑定
const beginRoleFunc = async (role_id: number) => {
    roleFunc.model.role_id = role_id;
    const funcs = await RoleAPI.getRoleFuncs(role_id);
    roleFunc.currentFuncs = funcs;
    nextTick(() => {
        roleFunc.isSetting = true;
        nextTick(() => echoFuncs());
    });
};
//确定
const saveRoleFunc = async () => {
    const checkedKeys = [...treeRef.value.getHalfCheckedKeys(), ...treeRef.value.getCheckedKeys(),];
    if (checkedKeys.length > 1) checkedKeys.shift();
    roleFunc.model.role_func_ids = checkedKeys.join(',');
    await RoleAPI.saveRoleFuncs(roleFunc.model);
    roleFunc.isSetting = false;
    ElMessage({ type: 'success', message: '角色功能修改成功', });
};
const update = (item: Vm.Role) => {
    formRef.value?.resetFields();
    roleModel.role_name = item.role_name;
    roleModel.role_id = item.role_id;

    nextTick(() => roleFunc.isCart = true);
};
const add = () => {
    formRef.value?.resetFields();
    roleModel.role_id = 0;
    roleModel.role_name = "";

    nextTick(() => roleFunc.isCart = true);
};

const remove = async (id: number) => {
    try {
        ElMessageBox.confirm(
            `确定删除?`,
            "Tip",
            {
                showClose: false,
                type: 'warning',
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            })
            .then(async () => {
                await RoleAPI.remove(id);
                const i = roleStore.roleList.findIndex(item => item.role_id === id);
                roleStore.roleList.splice(i, 1);
                ElMessage({
                    message: "删除成功！", type: 'success'
                })
            })
            .catch((e) => { console.log(e) })
    } catch (e) { console.log(e) };
}

const ok = async () => {
    try {
        await formRef.value?.validate();
        if (roleModel.role_id === 0) {
            const role_id = await RoleAPI.add(roleModel);
            roleStore.roleList.push({
                role_id: role_id,
                role_name: roleModel.role_name
            })
            ElMessage({ message: `${roleModel.role_name}添加成功！`, type: 'success' });
        } else {
            await RoleAPI.update(roleModel);
            const i = roleStore.roleList.findIndex(item => item.role_id === roleModel.role_id)
            roleStore.roleList.splice(i, 1, {
                role_id: roleModel.role_id,
                role_name: roleModel.role_name
            });
            ElMessage({ message: `${roleModel.role_name}编辑成功！`, type: 'success' });
        }
        roleFunc.isCart = false;
    } catch (e) { console.log(e) };
};
</script>

<template>
    <el-row :gutter="20">
        <el-col :span="28">
            <div v-for="item in roleStore.roleList" :key="item.role_id">
                <div class="orgin">
                    <el-icon>
                        <User />
                    </el-icon>
                    <h3 v-text="item.role_name"></h3>
                    <div class="new">
                        <span :icon="Edit" @click="update(item)">编辑</span>
                        <span :icon="Setting" @click="beginRoleFunc(item.role_id)">绑定功能</span>
                        <span :icon="Delete" @click="remove(item.role_id)">删除</span>
                    </div>
                </div>
            </div>
            <div class="add" @click="add" style="width:365px">
                <el-icon size="30px">
                    <Plus />
                </el-icon>
            </div>
        </el-col>
    </el-row>
    <el-drawer :model-value="roleFunc.isSetting" :show-close="false" :close-on-click-modal="false"
        :close-on-press-escape="false">
        <el-container>
            <el-header height="30px">
                <h6>角色功能绑定</h6>
            </el-header>
            <el-main>
                <el-tree ref="treeRef" class="custom-tree" :expand-on-click-node="false" :default-expand-all="true"
                    :data="funcStore.treeData" :props="{ label: 'func_name' }" show-checkbox node-key="func_id">
                </el-tree>
            </el-main>
            <el-footer height="40px">
                <el-button :icon="RefreshRight" type="warning" @click="echoFuncs">重置</el-button>
                <el-button :icon="Finished" type="success" @click="saveRoleFunc">确定</el-button>
                <el-button :icon="Close" @click="roleFunc.isSetting = false">取消</el-button>
            </el-footer>
        </el-container>
    </el-drawer>
    <el-dialog :model-value="roleFunc.isCart" title="功能修改" width="30%" draggable>
        <el-form ref="formRef" :model="roleModel" :rules="rules" status-icon>
            <el-form-item prop="role_name" label="角色名称" :label-width="formLabelWidth">
                <el-input v-model="roleModel.role_name" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="roleFunc.isCart = false">取消</el-button>
                <el-button type="primary" @click="ok">保存</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<style scoped>
.el-row {
    width: 100%;
}

.el-col {
    display: flex;
    flex-wrap: wrap;
}

.el-container {
    position: absolute;
    top: 0;
    right: 0;
    width: 100%;
    height: 100%;
}

h6 {
    font-size: 15px;
    font-family: "宋体";
    line-height: 30px;
    text-align: center;
}

.el-footer {
    margin-top: 10px;
    text-align: right;
}

.el-main {
    border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    border-top: 1px solid rgba(0, 0, 0, 0.1);
}

.orgin {
    width: 350px;
    height: 120px;
    padding: 20px;
    box-sizing: border-box;
    margin-right: 20px;
    margin-bottom: 20px;
    border-radius: 10px;
    background-color: #67c23a;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
}

.new {
    width: 350px;
    height: 120px;
    padding: 20px;
    margin-right: 20px;
    box-sizing: border-box;
    border-radius: 10px;
    background-color: #000;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    top: 0;
    left: 0;
    opacity: 0;
}

span {
    margin-right: 20px;
    cursor: pointer;
}

span:hover {
    color: #e6a23c;
    font-weight: 700;
}

.new:hover {
    opacity: 0.7;
    color: #fff;
}

.el-icon {
    margin-right: 15px;
    font-size: 25px;
    vertical-align: bottom;
}

.hovor {
    background-color: #757F89;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 358px;
    height: 120px;
    padding: 20px;
    box-sizing: border-box;
    border-radius: 10px;
    margin-right: 20px;
}

.text {
    font-size: 20px;
}

.add {
    width: 350px !important;
    height: 120px;
    padding: 20px;
    box-sizing: border-box;
    margin-right: 20px;
    border-radius: 10px;
    background-color: #fff;
    color: #67c23a;
    display: flex;
    justify-content: center;
    align-items: center;
    box-shadow: 0 0 10px 1px rgb(223, 219, 219);
}
</style>
